package com.edu.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.PrintWriter;
import java.io.StringWriter;

/*
 * @Author:princess
 * @Date 2023/12/6 12 06 18:44
 *
 */
@Controller
public class ExceptionController {
    //不管哪一个方法出错了，都能返回一个友好的错误页面，通过日志 纪录了错误信息
//    @ExceptionHandler(Exception.class)
//    public ModelAndView handlerException(Exception e){
//        ModelAndView mv = new ModelAndView();
//        //通过日志 纪录错误信息
//        StringWriter sw = new StringWriter();
//        PrintWriter pw = new PrintWriter(sw);
//        e.printStackTrace(pw);
//        //换成 logger 以日志的形式输出到文件
//        System.out.println(sw.toString());
//        //调到错误页面并附带错误信息
//        mv.addObject("error",sw.toString());
//        mv.setViewName("error");
//        return mv;
//    }

    @RequestMapping("/exception01")
    public String excption01(){
        String str = null;
        System.out.println(str.length());
        return "index";
    }

//    //捕获精确的异常
//    @ExceptionHandler(MissingServletRequestParameterException.class)
//    public ModelAndView handlerException02(Exception e){
//        ModelAndView mv = new ModelAndView();
//        System.out.println("缺少必要的参数");
//        mv.setViewName("error");
//        return mv;
//    }

    @RequestMapping("/exception02")
    public String excption02(@RequestParam String username){
        System.out.println(username);
        return "index";
    }
}
